﻿using UnityEngine;
using UnityEngine.UI;
using Unity.XR.PXR;         // PICO SDK
using Pico.Platform;
using Pico.Platform.Models;
using System;
using System.IO;
using System.Collections;
using System.Threading.Tasks;
using UnityEngine.Android;

public class CameraON : MonoBehaviour
{
    public Button seeThroughButton;   // 透视模式按钮
    public Button captureButton;      // 截屏按钮
    public Text buttonText;           // 透视模式按钮的文本
    private bool isSeeThroughOn = false;

    // 新增会话 ID 变量，用于记录高亮会话
    private string currentSessionId = "";
    // 自动截屏状态变量
    private bool isCapturing = false;
    private Coroutine captureCoroutine;

    private void Start()
    {
        CheckAndRequestPermissions(); // 确保权限已获取

        // 先初始化 SDK，再开启会话
        InitializePicoSDK();

        // 绑定按钮事件
        if (seeThroughButton != null)
        {
            seeThroughButton.onClick.AddListener(ToggleSeeThrough);
        }

        if (captureButton != null)
        {
            // 修改按钮事件为切换自动截屏功能
            captureButton.onClick.AddListener(ToggleCaptureScreen);
        }

        UpdateButtonUI();
    }

    // 初始化 PICO SDK
    private void InitializePicoSDK()
    {
        if (!CoreService.IsInitialized())
        {
            Debug.Log("🚀 正在初始化 PICO SDK...");
            CoreService.AsyncInitialize().OnComplete(initResult =>
            {
                if (initResult.IsError)
                {
                    Debug.LogError("❌ PICO SDK 初始化失败: " + initResult.Error.Message);
                }
                else
                {
                    Debug.Log("✅ PICO SDK 初始化成功");
                    // SDK 初始化成功后再开启会话
                    StartSession();
                }
            });
        }
        else
        {
            // 如果已初始化，直接开启会话
            StartSession();
        }
    }

    // 自动开启高亮会话
    private void StartSession()
    {
        Debug.Log("🚀 正在开启高亮会话...");
        HighlightService.StartSession().OnComplete(m =>
        {
            if (m.IsError)
            {
                Debug.LogError("❌ 开启会话失败: " + m.Error.Message);
                return;
            }
            currentSessionId = m.Data;
            Debug.Log("✅ 会话开启成功，SessionId: " + currentSessionId);
        });
    }

    // **检查并请求权限**
    private void CheckAndRequestPermissions()
    {
        if (!Permission.HasUserAuthorizedPermission(Permission.Camera))
        {
            Permission.RequestUserPermission(Permission.Camera);
        }

        if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
        {
            Permission.RequestUserPermission(Permission.ExternalStorageWrite);
        }
    }

    // **开启摄像头（透视模式）**
    public void cmeraON_click()
    {
        PXR_Boundary.SetGuardianSystemDisable(false);
        Debug.Log("📷 摄像头（透视模式）已开启");
        UpdateButtonUI();
    }

    // **切换透视模式**
    void ToggleSeeThrough()
    {
        isSeeThroughOn = !isSeeThroughOn;
        PXR_Boundary.EnableSeeThroughManual(isSeeThroughOn);
        Debug.Log("👁️ 透视模式：" + (isSeeThroughOn ? "开启" : "关闭"));
        UpdateButtonUI();
    }

    // **更新按钮 UI**
    void UpdateButtonUI()
    {
        if (buttonText != null)
        {
            buttonText.text = isSeeThroughOn ? "关闭透视模式" : "开启透视模式";
        }
    }

    // 切换自动截屏功能：启动或停止协程
    public void ToggleCaptureScreen()
    {
        if (!isCapturing)
        {
            // 开始自动截屏
            Debug.Log("🚀 启动自动截屏...");
            isCapturing = true;
            captureCoroutine = StartCoroutine(PeriodicallyCapture());
        }
        else
        {
            // 停止自动截屏
            Debug.Log("⏸️ 停止自动截屏");
            isCapturing = false;
            if (captureCoroutine != null)
            {
                StopCoroutine(captureCoroutine);
                captureCoroutine = null;
            }
        }
    }

    // 每两秒执行一次截屏
    IEnumerator PeriodicallyCapture()
    {
        while (true)
        {
            // 检查会话是否已经开启
            if (string.IsNullOrEmpty(currentSessionId))
            {
                Debug.LogError("❌ 当前会话未开启，无法截屏！");
            }
            else if (!CoreService.IsInitialized())
            {
                Debug.LogError("❌ PICO SDK 未初始化，无法截屏！");
            }
            else
            {
                DoCaptureScreen();
            }
            yield return new WaitForSeconds(2f);
        }
    }

    // 执行截屏并保存
    void DoCaptureScreen()
    {
        Debug.Log("📸 开始截屏...");
        HighlightService.CaptureScreen().OnComplete(m =>
        {
            if (m.IsError)
            {
                Debug.LogError("❌ 截屏失败: " + m.Error);
                return;
            }

            CaptureInfo captureInfo = m.Data;
            Debug.Log("✅ 截屏成功，保存路径: " + captureInfo.ImagePath);

            // **指定保存路径**
            string targetDirectory = "/storage/emulated/0/Pictures/PICO_Screenshots/";
            string targetPath = targetDirectory + "screenshot_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".png";

            // **确保目标文件夹存在**
            if (!Directory.Exists(targetDirectory))
            {
                Directory.CreateDirectory(targetDirectory);
            }

            // **复制文件到指定目录**
            try
            {
                File.Copy(captureInfo.ImagePath, targetPath, true);
                Debug.Log("✅ 截图已保存至: " + targetPath);
            }
            catch (Exception e)
            {
                Debug.LogError("❌ 保存截图失败: " + e.Message);
            }
        });
    }
}
